package com.lzc.tlmail.tlmailsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.lzc.common.to.es.SkuEsModel;
import com.lzc.tlmail.tlmailsearch.config.ElasticsearchConfig;
import com.lzc.tlmail.tlmailsearch.constant.EsConstant;
import com.lzc.tlmail.tlmailsearch.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lzc
 * @create 2020-09-21 21:57
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    /**
     * 商品上架保存到es
     * @param skuEsModels
     */
    @Override
    public boolean saveProduct(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到es
        //1给es中简历索引 product 建立好映射关系
        //2给es中保存
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            //1 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        //todo 如果批量错误
        boolean b = bulk.hasFailures();
        //这里是吧批量的返回信息处理
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成｛｝",collect);
        return b;
    }
}
